package g

import (
	"sync"

	"github.com/toolkits/file"
	"encoding/json"
)

type GlobalConfig struct {
	Debug        bool             `json:"debug"`
	AgentVersion string           `json:"agentversion"`
	Redis        *RedisConfig     `json:"redis"`
	RPCClient    *RPCClientConfig `json:"rpcclient"`
	RPC          *RPCConfig       `json:"rpc"`
	HTTP         *HTTPConfig      `json:"http"`
}

type RPCClientConfig struct {
	Addr    string `json:"addr"`
	Timeout int    `json:"timeout"`
}

type RPCConfig struct {
	Enabled bool   `json:"enabled"`
	Listen  string `json:"listen"`
}

type HTTPConfig struct {
	Enabled bool   `json:"enabled"`
	Listen  string `json:"listen"`
}

type RedisConfig struct {
	Addr string `json:"addr"`
	Pwd  string `json:"pwd"`
}

var (
	ConfigFile string
	gconfig    *GlobalConfig
	lock       = new(sync.RWMutex)
)

func Config() *GlobalConfig {
	lock.RLock()
	defer lock.RUnlock()
	return gconfig
}

/**
	xiaohan:2018-5-11
	删除变量 ConfigFile var c GlobalConfig
 */
func ParseConfig(cfg string) {
	if cfg == "" {
		Logger.Error("use -c to specify configuration file ")
	}

	if !file.IsExist(cfg) {
		Logger.Error("config file: ", cfg, " is not existent. maybe you need `mv cfg.example.json cfg.json`")
	}

	//ConfigFile = cfg

	configContent, err := file.ToTrimString(cfg)
	if err != nil {
		Logger.Error("read config file: ", cfg, " fail:", err)
	}

	//var c GlobalConfig
	err = json.Unmarshal([]byte(configContent), &gconfig)
	if err != nil {
		Logger.Error("parse config file: ", cfg, " fail:", err)
	}

	lock.Lock()
	defer lock.Unlock()

	//gconfig = &c

	Logger.Info("read config file: ", cfg, " successfully")
}
